using System.Collections.Generic;
using Microsoft.MediaCenter.Hosting;
using System.Threading;
using System;

namespace RMC
{
	public class MyAddIn : IAddInModule, IAddInEntryPoint
	{
		private TcpServer tcpServer = null;
		private TcpInfoServer tcpInfoServer = null;
		private int port = 10000;
		private EventWaitHandle waitHandle = new ManualResetEvent(false);

		public void Initialize(Dictionary<string, object> appInfo, Dictionary<string, object> entryPointInfo)
		{
			waitHandle.Reset();
		}

		public void Uninitialize()
		{
			waitHandle.Set();
		}

		public void Launch(AddInHost host)
		{
			if (host != null)
			{
				//host.MediaCenterEnvironment.Dialog("Hello...", "Hello world", new object[] { Microsoft.MediaCenter.DialogButtons.Ok }, 5, true, null, delegate(Microsoft.MediaCenter.DialogResult dialogResult) { });
			}
			/*
			if (host != null && host.ApplicationContext != null)
			{
				host.ApplicationContext.SingleInstance = true;
			}
			Application app = new Application(host);
			app.Start();
			*/
			

			try
			{
				System.Threading.Thread.CurrentThread.Priority = ThreadPriority.Lowest;
				
				tcpServer = new TcpServer(port);
				tcpInfoServer = new TcpInfoServer(port + 1000);

				tcpServer.Start();
				tcpInfoServer.Start();
				
				waitHandle.WaitOne();

				tcpServer.Stop();
				tcpInfoServer.Stop();
			}
			catch(Exception ex)
			{
				//System.Diagnostics.Debugger.Log(0, "RMC", "\n" + ex.ToString() + "\n");
				host.MediaCenterEnvironment.Dialog("RMC", ex.Message, new object[] { Microsoft.MediaCenter.DialogButtons.Ok }, 5, true, null, delegate(Microsoft.MediaCenter.DialogResult dialogResult) { });
			}
		}
	}
}